﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using SBlogCore.Common.Models;

namespace SBlogCore.Common.Filters
{
    [SkipScan]
    public class RequestAsyncActionFilter : IAsyncActionFilter, IOrderedFilter
    {
        /// <summary>
        /// 过滤器排序
        /// </summary>
        internal const int FilterOrder = 9999;

        /// <summary>
        /// 排序属性
        /// </summary>
        public int Order => FilterOrder;

        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            var actionContext = await next();
            if (actionContext.Exception==null)
            {
                var result = OnSucceeded(actionContext);
                actionContext.Result = result;
            }
        }
        public IActionResult OnSucceeded(ActionExecutedContext context)
        {
            object res ;
            object data;
            // 处理内容结果
            if (context.Result is ContentResult contentResult) data = contentResult.Content;
            // 处理对象结果
            else if (context.Result is ObjectResult objectResult) data = objectResult.Value;
            else if (context.Result is EmptyResult) data = new object();
            else return null!;
            if (data!=null&&data.GetType().Name== typeof(ResultEntity<>).Name)
            {
                res = data ;
            }
            else {
                res = ResultEntity<object?>.Success("操作成功", data);
            }
            return new JsonResult(res);
        }
    }
}
